import 'package:dio/dio.dart';

class UserAPI {
  final Dio _dio;

  UserAPI(this._dio);

  // 获取发送短信的凭证
  Future<dynamic> verifyCode() async {
    Response res = await _dio.get('/verify_code');

    return res.data;
  }

  // 发送验证码
  Future<dynamic> sendCaptcha({ String phone = '', String key = '', String type = '' }) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "phone": phone,
      "key": key,
      "type": type
    });
    Response res = await _dio.post('/register/verify', data: formData);

    return res.data;
  }

  // 短信登陆
  Future<dynamic> register({ String phone = '', String captcha = '' }) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "phone": phone,
      "captcha": captcha,
    });
    Response res = await _dio.post('/login/mobile', data: formData);

    return res.data;
  }

  // 获取用户信息
  Future<dynamic> getInfo() async {
    Response res = await _dio.get('/user');
    print('--- 获取用户信息 ---');
    // print(res.data);
    return res.data;
  }

  // 用户退出
  Future<dynamic> logout() async {
    Response res = await _dio.get('/logout');

    return res.data;
  }

  // 上传图片
  Future<dynamic> uploadImage({ String imagePath = '', String filename = '' }) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(imagePath, filename: filename),
    });
    Response res = await _dio.post('/upload/image', data: formData);

    return res.data;
  }

  // 保存用户信息
  Future<dynamic> save(String avatar, String nickname) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "avatar": avatar,
      "nickname": nickname,
    });
    Response res = await _dio.post('/user/edit', data: formData);

    return res.data;
  }

  // 修改密码
  Future<dynamic> changePassword(String phone, String password, String captcha) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "account": phone,
      "password": password,
      "captcha": captcha,
    });
    Response res = await _dio.post('/register/reset', data: formData);

    return res.data;
  }

  // 用户登录
  Future<dynamic> login(String phone, String password) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "account": phone,
      "password": password,
    });
    Response res = await _dio.post('/login', data: formData);

    return res.data;
  }
}